﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Web.Security;

using Qianwei.Model;
using Qianwei.Biz;
using Qianwei.Common.Extension;
using Qianwei.Common;

namespace Qianwei.Web
{
    public partial class User_Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            txtLoginName.Focus();
        }

        #region Method
        private string CheckInput()
        {
            string strErr = string.Empty;
            if (txtLoginName.Text.Trim().Length == 0)
            {
                strErr = "请输入登录名";
            }
            else if (txtPassword.Text.Trim().Length == 0)
            {
                strErr = "请输入密码";
            }
            else if (txtValiCode.Text.Trim().Length == 0)
            {
                strErr = "请输入验证码";
            }
            else if (Session["CheckCode"] == null)
            {
                strErr = "系统超时,请稍后重试";
            }
            else if (txtValiCode.Text.Trim() != Session["CheckCode"].ToString())
            {
                strErr = "请输入正确的验证码";
            }
            return strErr;
        }

        private void UserLogin()
        {
            if (UserInfoManager.Instance.UserIsExists(txtLoginName.Text.Trim(), Util.MD5Encrypt(txtPassword.Text.Trim())))
            {
                FormsAuthentication.SetAuthCookie(txtLoginName.Text.Trim(), true);

                //清除验证码;
                if (Session["CheckCode"] != null)
                {
                    Session.Remove("CheckCode");
                }
                UserInfoManager.Instance.UpdateLoginInfo(txtLoginName.Text.Trim(), Util.GetIP());
                if (Request["ReturnUrl"] != null)
                {
                    //Response.Redirect(string.Format("Admins/Main.aspx?ReturnUrl={0}", Request["ReturnUrl"]));
                    Response.Redirect(Request["ReturnUrl"]);
                }
                else
                {
                    Response.Redirect("Admins/Main.aspx");
                }
            }
            else
            {
                Util.PageAlert("用户名或密码错误");
            }
        }
        #endregion

        #region Event
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            string result = CheckInput();
            if (result.Length > 0)
            {
                Util.PageAlert(result);
            }
            else
            {
                UserLogin();
            }
        }
        #endregion
    }
}